#!/bin/bash

print_velocity() {
	interface=$(ip route get 8.8.8.8 2>/dev/null| awk '{print $5}')
	rt_line=$(grep $interface /proc/net/dev | cut -d':' -f2 | awk '{print "recv_bytes="$1, "send_bytes="$9}')
	eval $rt_line
	time=$(date +%s%N)

	if [ -z $old_time ]; then
		old_time=0
	fi
	if [ -z $old_recv_bytes ]; then
		old_recv_bytes=0
	fi
	if [ -z $old_send_bytes ]; then
		old_send_bytes=0
	fi
	echo $old_time
	echo $time
	echo $old_recv_bytes
	echo $recv_bytes
	echo $old_send_bytes
	echo $send_bytes
	
	vel_KB=$(echo "10000000000*($recv_bytes-$old_recv_bytes)/1024/($time-$old_time)" | bc)
	if [ "$vel_KB" -gt 1024 ]; then
		echo $(echo "scale=2; $vel_KB/1024" | bc)MB/s
	else
		echo ${vel_KB}KB/s
	fi

	old_time=$time
	old_recv_bytes=$recv_bytes
	old_send_bytes=$send_bytes
}

print_velocity
